package ch.il07.utils.logging;

import java.util.LinkedList;
import java.util.List;

import ch.il07.utils.ConverterProperties;
import ch.il07.utils.logging.impl.EmptyLogger;

public class LoggerHelper {

	private static Logger logger;

	private static final Object LOCK = new Object();

	public static Logger getLogger() {
		if (logger == null) {
			synchronized (LOCK) {
				if (logger == null) {
					logger = getImplementation();
				}
			}
		}
		return logger;
	}

	private static Logger getImplementation() {
		List<Class<ChainLogger>> loggers = getConfiguredLoggers();
		if (loggers.size() == 0) {
			return new EmptyLogger();
		}
		ChainLogger logger1, logger2;
		try {
			logger2 = logger1 = loggers.get(0).newInstance();
			for (int i = 1; i < loggers.size(); i++) {
				logger2 = logger2.setNext(loggers.get(1).newInstance());
			}
			return logger1;
		} catch (InstantiationException e) {
			throw new LoggerException(e);
		} catch (IllegalAccessException e) {
			throw new LoggerException(e);
		}
	}

	@SuppressWarnings("unchecked")
	private static List<Class<ChainLogger>> getConfiguredLoggers() {
		List<Class<ChainLogger>> loggers = new LinkedList<Class<ChainLogger>>();
		String paramPattern = "logger[%d]";
		for (int i = 0; i < 10; i++) {
			String param = String.format(paramPattern, i);
			String className = ConverterProperties.getProperty(param);
			if (className == null) {
				break;
			} else {
				Class<ChainLogger> loggerClass;
				try {
					loggerClass = (Class<ChainLogger>) Class.forName(className);
				} catch (ClassNotFoundException e) {
					throw new LoggerException(
							"error while trying to make a class for name ["
									+ className + "]", e);
				}
				loggers.add(loggerClass);
			}
		}
		return loggers;
	}

}
